package com.example.web.websocket.handle;

import com.example.web.websocket.entity.User;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Created by YangGang on 2021/8/2 15:46。
 */
public class UserHandle {
    private static UserHandle userHandle = new UserHandle();
    // <key,user>
    private Map<String, User> userMap = new ConcurrentHashMap<>();

    private UserHandle() {
    }

    public static UserHandle getHandle() {
        return userHandle;
    }

    public void addUser(User user) {
        userMap.put(user.getKey(), user);
    }

    public void removeUser(String key) {
        userMap.remove(key);
    }

    public User findUser(String key) {
        return userMap.get(key);
    }

    public List<User> findGroupUser(String group) {
        List<User> collect = userMap.values().stream()
                .filter(u -> group.equals(u.getGroup()))
                .collect(Collectors.toList());
        return collect;
    }

    public int sum() {
        return userMap.size();
    }
}
